import Store from '@/store'
import Utils from '@/uni_modules/yingbing-ui/js_sdk/util.js'
import Modules from '@/plugins/modules'
import Router from '@/plugins/router';
import Config from '@/assets/js/config.js';
import inSources from '@/assets/api/source.js';
import { statement, extractPattern } from '@/assets/api/global.js'

const { getters, commit, dispatch } = Store
const { suffix } = Utils
const { resources, ERR_OK, ERR_FALSE, app, hotspot } = Config
export default {
	//设置手机壁纸
	setWall (type = 'all', path) {
		let main = plus.android.runtimeMainActivity()
		let WallpaperManager = plus.android.importClass("android.app.WallpaperManager")
		let BitmapFactory = plus.android.importClass("android.graphics.BitmapFactory")
		let wallpaperManager = WallpaperManager.getInstance(main)
		plus.android.importClass(wallpaperManager)
		let filePath = plus.io.convertLocalFileSystemURL(path)
		let bitmap = BitmapFactory.decodeFile(filePath)
		try {
			if ( type == 'all' || type == 'wallpaper' ) wallpaperManager.setBitmap(bitmap) //设置壁纸
			if ( type == 'all' || type == 'lock' ) wallpaperManager.setBitmap(bitmap, null, true, WallpaperManager.FLAG_LOCK) //设置锁屏
			plus.android.invoke(bitmap, 'recycle')
			bitmap = null
			uni.showToast({
				title: "壁纸设置成功",
				icon: "none"
			})
		} catch (e) {
			uni.showToast({
				title: "壁纸设置失败",
				icon: "none"
			})
		}
	},
	//文件分享
	async shareFile (path) {
		if ( path ) {
			try{
				let main = plus.android.runtimeMainActivity();
				let Intent = plus.android.importClass("android.content.Intent");
				let MimeTypeMap = plus.android.importClass("android.webkit.MimeTypeMap");
				const src = await this.selectReferer(path, true)
				let file = plus.android.newObject('java.io.File', plus.io.convertLocalFileSystemURL(src))
				let accept = MimeTypeMap.getSingleton().getMimeTypeFromExtension(suffix(plus.android.invoke(file, 'getName')))
				let shareIntent = new Intent(Intent.ACTION_SEND);
				shareIntent.putExtra(Intent.EXTRA_STREAM, plus.io.convertLocalFileSystemURL(src));
				shareIntent.setType(accept ? accept : "*/*");
				main.startActivity(Intent.createChooser(shareIntent,"分享到"))
			}catch(e){
				uni.showToast({
					title: e.toString(),
					icon: 'none'
				})
			}
		} else {
			uni.showToast({
				title: '文件路径无效',
				icon: 'none'
			})
		}
	},
	//网站分享
	shareWeb (params) {
		if ( !params ) {
			uni.showToast({
				title: '未传入分享对象',
				icon: 'none'
			})
			return
		}
		if ( !params.shareUrl ) {
			uni.showToast({
				title: '未传入分享链接',
				icon: 'none'
			})
			return
		}
		uni.navigateTo({
			url: '/modules/poster?params=' + encodeURIComponent(JSON.stringify(params))
		})
	},
	//预览图片
	async previewImage ({urls = [], current = 0, indicator = 'default', loop = false, success, fail, complete}) {
		let newUrls = []
		for( let url of urls ) {
			newUrls.push(await this.selectReferer(url))
		}
		uni.previewImage({
			urls: newUrls,
			current: current,
			longPressActions: {
				itemList: ['保存图片', '分享图片', '设为壁纸', '设为锁屏', '设为锁屏和壁纸'],
				success: (data) => {
					uni.showLoading({
						title: '图片下载中'
					})
					uni.downloadFile({
						url: urls[data.index],
						header: {
							Referer: urls[data.index]
						},
						success: (ret) => {
							uni.hideLoading()
							if (ret.statusCode === 200) {
								if ( data.tapIndex == 0 ) {
									uni.saveImageToPhotosAlbum({
										filePath: ret.tempFilePath,
										success: () => {
											uni.showToast({
												title: '已保存到相册',
												icon: 'none'
											})
										},
										fail: () => {
											uni.showToast({
												title: '保存到相册失败',
												icon: 'none'
											})
										}
									});
								} else if ( data.tapIndex == 1 ) {
									this.shareFile(ret.tempFilePath)
								} else {
									this.setWall(data.tapIndex == 2 ? 'wallpaper' : data.tapIndex == 3 ? 'lock' : 'all', ret.tempFilePath)
								}
							} else {
								uni.showToast({
									title: '图片下载失败',
									icon: 'none'
								})
							}
						},
						fail: (err) => {
							uni.showToast({
								title: '网络错误',
								icon: 'none'
							})
						}
					})
				},
				fail: function(err) {
					console.log(err.errMsg);
				}
			}
		})
	},
	//导出JSON
	async deriveSource (source) {
		return await this.writeAndExportFile(source.title + '.json', this.sourceJsToText(source))
	},
	//写入并导出文件
	writeAndExportFile (fileName, text) {
		return new Promise(resolve => {
			plus.io.requestFileSystem(plus.io.PRIVATE_DOC, ( fs ) => {
				let file = plus.android.newObject("java.io.File", fs.root.fullPath + fileName);
				plus.android.invoke(file, 'createNewFile')
				let fileOutputStream = plus.android.newObject("java.io.FileOutputStream", file);
				let outputStreamWriter = plus.android.newObject("java.io.OutputStreamWriter", fileOutputStream, "utf-8");
				let bufferedWriter = plus.android.newObject("java.io.BufferedWriter", outputStreamWriter);
				plus.android.invoke(bufferedWriter, 'write', text)
				plus.android.invoke(bufferedWriter, 'close')
				resolve({
					status: true,
					fileName: plus.android.invoke(file, 'getName'),
					root: fs.root.fullPath
				})
			}, ( e ) => {
				resolve({
					status: false,
					msg: e.message.toString() || '创建文件失败'
				})
			});
		})
	},
	//来源JS对象转文本
	sourceJsToText (source) {
		let text = '{'
		Object.keys(source).forEach(key => {
			if ( Utils.typeof(source[key]) == 'Array' ) {
				let requestText = '['
				source[key].forEach((rules, i) => {
					let rulesText = '{'
					Object.keys(rules).forEach(k => {
						if ( typeof rules[k] == 'string' ) {
							rulesText += '"' + k + '":"' + rules[k]+ '",'
						} else {
							rulesText += '"' + k + '":' + rules[k] + ','
						}
					})
					rulesText = rulesText.slice(0, rulesText.length-1)
					rulesText += '}' + (i < source[key].length - 1 ? ',' : '')
					requestText += rulesText
				})
				requestText += ']'
				text += '"' + key + '":' + requestText + ','
			} else if ( Utils.typeof(source[key]) == 'Object' ) {
				let funcText = '{'
				Object.keys(source[key]).forEach(k => {
					funcText += '"' + k + '":' + source[key][k].toString() + ','
				})
				funcText = funcText.slice(0, funcText.length-1)
				funcText += '}'
				text += '"' + key + '":' + funcText + ','
			} else {
				if ( typeof source[key] == 'string' ) {
					text += '"' + key + '":"' + source[key] + '",'
				} else {
					text += '"' + key + '":' + source[key] + ','
				}
			}
		})
		text += '}'
		return text
	},
	//打开详情
	async openDetail (params, animationType = 'slide-in-right') {
		if ( !params ) {
			uni.showToast({
				title: '未传入资源对象',
				icon: 'none'
			})
			return
		}
		if ( params.isVip ) {
			uni.showToast({
				title: '付费资源请支持正版',
				icon: 'none'
			})
			return
		}
		const query = encodeURIComponent(JSON.stringify(params))
		const index = resources.findIndex(resource => resource.value == params.type)
		const detail = index > -1 ? resources[index].detail : ''
		if ( detail == 'gather' ) {
			Router.push({
				path: '/pages/gather/detail',
				animationType: animationType,
				query: { params: query }
			})
		} else if ( detail == 'character' ) {
			Router.push({
				path: '/pages/user/detail',
				animationType: animationType,
				query: { params: query }
			})
		} else if ( detail == 'book' ) {
			if ( params.source == 'local' ) {
				const records = getters['record/get']
				const recordIndex = records.findIndex(record => record.id == params.id)
				const record = recordIndex > -1 ? records[recordIndex] : {
					id: params.id,
					chapter: 1,
					start: 0,
					title: params.title,
					progress: 0,
				}
				commit('reader/setRecord', record)
				Router.push({
					path: params.type == 'novel' ? '/pages/book/reader' : '/pages/comic/reader',
					animationType: animationType,
					query: { params: query }
				})
			} else {
				Router.push({
					path: '/pages/book/detail',
					animationType: animationType,
					query: { params: query }
				})
			}
		} else if ( detail == 'video' ) {
			Router.push({
				path: '/pages/video/player',
				animationType: animationType,
				query: { params: query }
			})
		} else if ( detail == 'short' ) {
			Router.push({
				path: '/pages/short/player',
				animationType: animationType,
				query: { params: query }
			})
		} else if ( detail == 'live' ) {
			Router.push({
				path: '/pages/live/player',
				animationType: animationType,
				query: { params: query }
			})
		} else if ( detail == 'forum' ) {
			Router.push({
				path: '/pages/forum/detail',
				animationType: animationType,
				query: { params: query }
			})
		} else if ( detail == 'picture' ) {
			Router.push({
				path: '/pages/picture/detail',
				animationType: animationType,
				query: { params: query }
			})
		} else {
			uni.showToast({
				title: '未知数据类型，请确认类型是否配置正确',
				icon: 'none'
			})
		}
	},
	getType (type) {
		let index = resources.findIndex(re => re.value == type)
		return index > -1 ? resources[index].label : '未知类型'
	},
	getSources () {
		return inSources.concat(getters['source/get']).filter(s => getters['subscribe/get'].indexOf(s.id) == -1 && (!s.isAdult || getters['app/getAdult']) )
	},
	getDefaultAvatar (source) {
		return this.filterSource(source).logo || '/static/logo.png'
	},
	filterSource (source) {
		let sources = inSources.concat(getters['source/get'])
		let index = sources.findIndex(item => item.id == source)
		if ( index == -1 ) {
			return {
				id: source,
				title: app.name,
				logo: app.logo
			}
		} else {
			return sources[index]
		}
	},
	isCollection (id) {
		return getters['collection/get'].findIndex(collection => collection.id == id) > -1
	},
	toCollection (params) {
		if ( !params ) { return }
		Router.push({
			path: '/modules/collection',
			animationType: 'fade-in',
			query: {
				params: encodeURIComponent(JSON.stringify(params)),
			}
		})
	},
	isFollowee (id) {
		return getters['followee/get'].findIndex(followee => followee.id == id) > -1
	},
	//关注
	toFollowee (params) {
		if ( !params ) { return }
		const id = params.id
		if ( this.isFollowee(id) ) {
			dispatch('followee/remove', id)
		} else {
			dispatch('followee/save', Object.assign({}, params, {
				collectBy: 'default'
			}) )
		}
	},
	//设置防盗链
	selectReferer (src, flag = false, referer) {
		return new Promise(resolve => {
			let sources = this.getSources()
			sources = sources.filter(source => source.security)
			let referers = getters['referer/get']
			sources.forEach(source => {
				referers = referers.concat(source.security.split(',').map(s => s.trim()))
			})
			if ( referers.findIndex(referer => src.indexOf(referer) > -1) > -1 || flag || referer ) {
				const caches = getters['cache/get'];
				const index = caches.findIndex(cache => cache.id == src + '_referer')
				if ( index > -1 ) {
					const file = plus.android.newObject('java.io.File', plus.io.convertLocalFileSystemURL(caches[index].src));
					if ( plus.android.invoke(file, 'exists') ) {
						resolve(caches[index].src)
						return
					} else {
						dispatch('cache/remove', caches[index].id)
					}
				}
				uni.downloadFile({
					header: {
						Referer: referer || src
					},
					url: src,
					success: res => {
						if (res.statusCode === 200) {
							dispatch('cache/add', {
								id: src + '_referer',
								src: res.tempFilePath,
								type: 'image'
							})
							resolve(res.tempFilePath)
						} else {
							resolve(src)
						}
					},
					fail: err => {
						resolve(src)
					}
				})
			} else { resolve(src) }
		})
	},
	openUrl (url) {
		// #ifdef APP-PLUS
		plus.runtime.openWeb(decodeURIComponent(url))
		// #endif
	},
	//根据资源获取相关作品
	async getRecome ({
		params={}, type, size=3, currentPage=1, pagings={}, isLastPages={}, requestTime=0, requestIndex=0, by = 'record'
	}) {
		let singles = params.id ? [params] : []
		let types = []
		if ( type == 'compress' ) {
			types = resources.map(res => res.value)
		} else {
			types = type.split(',').map(t => t.trim())
		}
		if ( by == 'collection' ) {
			let folders = getters['collection/get'].filter(collect => collect.type == 'collectfolder' && (!collect.isAdult || getters['app/getAdult']))
			folders.forEach(folder => {
				singles = singles.concat(folder.list.filter(sin => types.indexOf(sin.type) > -1 && (!sin.isAdult || getters['app/getAdult'])))
			})
		}
		if ( by == 'record' ) {
			singles = singles.concat(getters['record/get'].filter(record => types.indexOf(record.type) > -1 && (!record.isAdult || getters['app/getAdult']) ) )
		}
		let recome = JSON.parse(JSON.stringify(singles[requestIndex]))
		let sources = inSources.concat(getters['source/get']).filter(s => getters['subscribe/get'].indexOf(s.id) == -1 && (!s.isAdult || getters['app/getAdult']) )
		let arr = []
		let newArr = []
		sources.forEach(sou => {
			Object.keys(sou.request).forEach(key => {
				if ( sou.request[key] && sou.request[key].value && recome.source == sou.id && key == 'getRecome_' + recome.type ) {
					arr.push({
						data: Object.assign({}, recome, {
							source: sou.id,
							paging: pagings[key + '_' + sou.id + '_' + recome.id] || {},
							currentPage: currentPage
						}),
						key: key + '_' + sou.id + '_' + recome.id,
						name: key
					})
				}
			})
		})
		let tagList = recome.tag
		if ( recome.title ) {
			tagList.push(recome.title)
		}
		if ( recome.name ) {
			tagList.push(recome.name)
		}
		if ( recome.creator ) {
			tagList.push(recome.creator)
		}
		tagList = [...new Set(tagList)]
		let searchname = 'search_' + recome.type
		tagList.forEach(tag => {
			sources.forEach(sou => {
				Object.keys(sou.request).forEach(key => {
					let index = arr.findIndex(item => item.key == key + '_' + sou.id + '_' + tag)
					if ( key == searchname && sou.request[key] && sou.request[key].value && index == -1 ) {
						arr.push({
							data: {
								keyword: tag,
								source: sou.id,
								paging: pagings[key + '_' + sou.id + '_' + tag] || {},
								currentPage: currentPage
							},
							key: key + '_' + sou.id + '_' + tag,
							name: key
						})
					}
				})
			})
		})
		newArr = arr.slice(requestTime * size, ((requestTime + 1) * size)).filter(item => !isLastPages[item.key])
		let isEnd = (requestTime + 1) * size > arr.length - 1
		while ( newArr.length == 0 && !arr.every(item => isLastPages[item.key]) ) {
			requestTime++
			newArr = arr.slice(requestTime * size, ((requestTime + 1) * size)).filter(item => !isLastPages[item.key])
			isEnd = (requestTime + 1) * size > arr.length - 1
			if ( isEnd ) {
				requestTime = -1
				currentPage >= 0 ? currentPage++ : null
			}
		}
		newArr = newArr.map(item => {
			return Object.assign({}, item, {
				data: Object.assign({}, item.data, {
					currentPage: currentPage
				})
			})
		})
		if ( newArr.length > 0 ) {
			return await com_prepose(newArr).then(ress => {
				let list = []
				ress.forEach((res, i) => {
					if ( res.code == ERR_OK && res.data && res.data.list ) {
						list = list.concat(res.data?.list)
						pagings[newArr[i].key] = res.data.paging || {}
						isLastPages[newArr[i].key] = res.data.isLastPage || res.data.list.length == 0
					} else {
						pagings[newArr[i].key] = {}
						isLastPages[newArr[i].key] = true
					}
				})
				return {
					list: list,
					isLastPage: arr.every(item => isLastPages[item.key]) && requestIndex == singles.length - 1,
					pagings: pagings,
					isLastPages: isLastPages,
					requestTime: isEnd ? 0 : requestTime + 1,
					currentPage: isEnd ? currentPage + 1 : currentPage,
					requestIndex: isEnd ? requestIndex + 1 > singles.length - 1 ? 0 : requestIndex + 1 : requestIndex
				}
			})
		} else {
			return {
				list: [],
				isLastPage: true,
				pagings: {},
				isLastPages: {},
				requestTime: 0,
				currentPage: 1,
				requestIndex: 0
			}
		}
	},
	//根据关注获取相关作品
	async getFolloweeList ({
		type, size=3, currentPage=1, pagings={}, isLastPages={}, requestTime=0
	}) {
		let characters = []
		let types = []
		if ( type == 'compress' ) {
			types = resources.map(res => res.value)
		} else {
			types = type.split(',').map(t => t.trim())
		}
		let sources = inSources.concat(getters['source/get']).filter(s => getters['subscribe/get'].indexOf(s.id) == -1 && (!s.isAdult || getters['app/getAdult']) )
		let arr = []
		let newArr = []
		characters.forEach(character => {
			sources.forEach(sou => {
				Object.keys(sou.request).forEach(key => {
					if ( sou.request[key] && sou.request[key].value && character.source == sou.id &&  types.map(t => 'getCharacterWorksList_' + character.type + '_' + t ).indexOf(key) > -1 ) {
						arr.push({
							data: Object.assign({}, character, {
								source: sou.id,
								paging: pagings[key + '_' + sou.id + '_' + character.id] || {},
								currentPage: currentPage
							}),
							key: key + '_' + sou.id + '_' + character.id,
							name: key
						})
					}
				})
			})
		})
		newArr = arr.slice(requestTime * size, ((requestTime + 1) * size)).filter(item => !isLastPages[item.key])
		let isEnd = (requestTime + 1) * size > arr.length - 1
		while ( newArr.length == 0 && !arr.every(item => isLastPages[item.key]) ) {
			requestTime++
			newArr = arr.slice(requestTime * size, ((requestTime + 1) * size)).filter(item => !isLastPages[item.key])
			isEnd = (requestTime + 1) * size > arr.length - 1
			if ( isEnd ) {
				requestTime = -1
				currentPage >= 0 ? currentPage++ : null
			}
		}
		newArr = newArr.map(item => {
			return Object.assign({}, item, {
				data: Object.assign({}, item.data, {
					currentPage: currentPage
				})
			})
		})
		if ( newArr.length > 0 ) {
			return await com_prepose(newArr).then(ress => {
				let list = []
				ress.forEach((res, i) => {
					if ( res.code == ERR_OK && res.data && res.data.list ) {
						list = list.concat(res.data?.list)
						pagings[newArr[i].key] = res.data.paging || {}
						isLastPages[newArr[i].key] = res.data.isLastPage || res.data.list.length == 0
					} else {
						pagings[newArr[i].key] = {}
						isLastPages[newArr[i].key] = true
					}
				})
				return {
					list: list,
					isLastPage: arr.every(item => isLastPages[item.key]),
					pagings: pagings,
					isLastPages: isLastPages,
					requestTime: isEnd ? 0 : requestTime + 1,
					currentPage: isEnd ? currentPage + 1 : currentPage
				}
			})
		} else {
			return {
				list: [],
				isLastPage: true,
				pagings: {},
				isLastPages: {},
				requestTime: 0,
				currentPage: 1
			}
		}
	}
}